package com.guldan.jaina.manager;

import java.util.ArrayList;
import java.util.List;

import com.guldan.core.exception.BusinessException;
import com.guldan.jaina.dto.organization.OrganizationDTO;
import com.guldan.jaina.utils.UserUtils;
import com.guldan.mapper.db.entity.*;
import com.guldan.mapper.db.mapper.ProjectCategoryMapperExt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.project.ProjectDTO;
import com.guldan.jaina.dto.project.ProjectSearchDTO;
import com.guldan.jaina.dto.projectattach.ProjectAttachDTO;
import com.guldan.jaina.dto.projectextensionrelation.ProjectExtensionRelationDTO;
import com.guldan.jaina.dto.projecttagrelation.ProjectTagRelationDTO;
import com.guldan.jaina.utils.ProjectAttachDomainConvertUtils;
import com.guldan.jaina.utils.ProjectDomainConvertUtils;
import com.guldan.mapper.db.mapper.ProjectMapperExt;

/**
 * Created by Silas.
 * Date: 2016/11/7
 * Time: 22:55
 */
@Service
public class ProjectManager extends BaseManager {

    @Autowired
    private ProjectMapperExt projectMapperExt;

    @Autowired
    private ProjectTagRelationManager projectTagRelationManager;

    @Autowired
    private ProjectExtensionRelationManager projectExtensionRelationManager;

    @Autowired
    private ProjectAttachManager projectAttachManager;

    @Autowired
    private OrganizationManager organizationManager;

    @Autowired
    private ProjectCategoryManager projectCategoryManager;

    //获取单个项目信息
    public ProjectDTO get(Integer projectId) {
        ProjectDTO dto = ProjectDomainConvertUtils.convert(projectMapperExt.selectByPrimaryKey(projectId));

        //读取projecttag
        List<ProjectTagRelation> projectTagRelationList = projectTagRelationManager.getProjectTagRelationListByProjectId(projectId);
        List<ProjectTagRelationDTO> projectTagDTOList = new ArrayList<ProjectTagRelationDTO>();
        if (projectTagRelationList != null) {
            for (ProjectTagRelation projectTagRelation : projectTagRelationList) {
                ProjectTagRelationDTO projectTagRelationDTO = projectTagRelationManager.get(projectTagRelation.getProjectTagRelationId());
                projectTagDTOList.add(projectTagRelationDTO);
            }
        }
        dto.setProjectTagList(projectTagDTOList);

        //读取projectextensiondic
        List<ProjectExtensionRelation> projectExtensionRelationList = projectExtensionRelationManager.getProjectExtensionRelationListByProjectId(projectId);
        List<ProjectExtensionRelationDTO> projectExtensionRelationDTOList = new ArrayList<ProjectExtensionRelationDTO>();
        if (projectExtensionRelationList != null) {
            for (ProjectExtensionRelation projectExtensionRelation : projectExtensionRelationList) {
                projectExtensionRelationDTOList.add(projectExtensionRelationManager.get(projectExtensionRelation.getRelationId()));
            }
        }
        dto.setProjectDicList(projectExtensionRelationDTOList);

        //读取projectattach
        List<ProjectAttach> projectAttachList = projectAttachManager.getProjectAttachListByProjectId(projectId);
        List<ProjectAttachDTO> dtolist = new ArrayList<ProjectAttachDTO>();
        if (projectAttachList != null) {
            for (ProjectAttach projectAttach : projectAttachList) {
                dtolist.add(ProjectAttachDomainConvertUtils.convert(projectAttach));
            }
        }
        dto.setProjectAttach(dtolist);

        return dto;
    }

    //判断某个项目是否已经存在
    private Boolean checkExist(String projectCode) {
        ProjectExample example = new ProjectExample();
        ProjectExample.Criteria criteria = example.createCriteria();
        criteria.andProjectCodeEqualTo(projectCode);
        criteria.andIsDeleteEqualTo(false);
        int count = projectMapperExt.countByExample(example);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    //新增/更新单个项目，传入：ProjectDTO
    public ProjectDTO save(ProjectDTO dto) throws BusinessException {

        Project entity;
        if (dto.getProjectId() != null && dto.getProjectId() > 0) {
            entity = projectMapperExt.selectByPrimaryKey(dto.getProjectId());
            entity.setHandingProcedure(dto.getHandingProcedure());
            entity.setIsDelete(false);
            entity.setIsNeedOrgReview(dto.getIsNeedOrgReview());
            entity.setIsNeedTownReview(dto.getIsNeedTownReview());
            entity.setMoneyCalculateTypeCode(dto.getMoneyCalculateTypeCode());
            entity.setOrgCode(dto.getOrgCode());
            entity.setPayCycleCode(dto.getPayCycleCode());
            entity.setPayObjCode(dto.getPayObjCode());
            entity.setPayObjStr(dto.getPayObjStr());
            entity.setPayUnitCode(dto.getPayUnitCode());
            entity.setPolicyBasis(dto.getPolicyBasis());
            entity.setProjectCategoryId(dto.getProjectCategoryId());
            entity.setProjectCode(dto.getProjectCode());
            entity.setProjectName(dto.getProjectName());
            entity.setProjectNameZe(dto.getProjectNameZe());
            entity.setRemark(dto.getRemark());
            entity.setSubsidyMoney(dto.getSubsidyMoney());
            entity.setTotalFormula(dto.getTotalFormula());
            entity.setAllowOrgEntry(dto.getAllowOrgEntry());
            entity.setDisabled(dto.getDisabled());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            projectMapperExt.updateByPrimaryKeySelective(entity);
        } else {

            //判断是否存存在
            if (checkExist(dto.getProjectCode())) {
                throw new BusinessException("项目Code已存在");
            }
            entity = new Project();
            entity.setHandingProcedure(dto.getHandingProcedure());
            entity.setIsDelete(false);
            entity.setIsNeedOrgReview(dto.getIsNeedOrgReview());
            entity.setIsNeedTownReview(dto.getIsNeedTownReview());
            entity.setMoneyCalculateTypeCode(dto.getMoneyCalculateTypeCode());
            entity.setOrgCode(dto.getOrgCode());
            entity.setPayCycleCode(dto.getPayCycleCode());
            entity.setPayObjCode(dto.getPayObjCode());
            entity.setPayObjStr(dto.getPayObjStr());
            entity.setPayUnitCode(dto.getPayUnitCode());
            entity.setPolicyBasis(dto.getPolicyBasis());
            entity.setProjectCategoryId(dto.getProjectCategoryId());
            entity.setProjectCode(dto.getProjectCode());
            entity.setProjectId(dto.getProjectId());
            entity.setProjectName(dto.getProjectName());
            entity.setProjectNameZe(dto.getProjectNameZe());
            entity.setRemark(dto.getRemark());
            entity.setSubsidyMoney(dto.getSubsidyMoney());
            entity.setTotalFormula(dto.getTotalFormula());
            entity.setAllowOrgEntry(dto.getAllowOrgEntry());
            entity.setDisabled(dto.getDisabled());
            entity.setCreator(dto.getCreator());
            entity.setCreateTime(DateUtil.getCurrentTime());
            projectMapperExt.insertSelective(entity);
        }
        dto = ProjectDomainConvertUtils.convert(dto, entity);
        if (dto.getProjectTagList() != null && dto.getProjectTagList().size() > 0) {
            List<ProjectTagRelationDTO> projectTagList = projectTagRelationManager.saveList(dto.getProjectId(), dto.getProjectTagList());
            dto.setProjectTagList(projectTagList);
        }
        if (dto.getProjectDicList() != null && dto.getProjectDicList().size() > 0) {
            List<ProjectExtensionRelationDTO> projectDicList = projectExtensionRelationManager.saveList(dto.getProjectId(), dto.getProjectDicList());
            dto.setProjectDicList(projectDicList);
        }
        if (dto.getProjectAttach() != null && dto.getProjectAttach().size() > 0) {
            List<ProjectAttachDTO> projectAttachList = projectAttachManager.saveList(dto.getProjectId(), dto.getProjectAttach());
            dto.setProjectAttach(projectAttachList);
        }
        return dto;
    }

    //删除单个项目信息
    public Boolean delete(Integer projectId) {
        Project entity = projectMapperExt.selectByPrimaryKey(projectId);

        //删除project-tag-relation
        List<ProjectTagRelation> projectTagRelationList = projectTagRelationManager.getProjectTagRelationListByProjectId(projectId);
        if (projectTagRelationList != null) {
            for (ProjectTagRelation projectTagRelation : projectTagRelationList) {
                projectTagRelationManager.delete(projectTagRelation);
            }
        }

        //删除project-extension-relation
        List<ProjectExtensionRelation> projectExtensionRelationList = projectExtensionRelationManager.getProjectExtensionRelationListByProjectId(projectId);
        if (projectExtensionRelationList != null) {
            for (ProjectExtensionRelation projectExtensionRelation : projectExtensionRelationList) {
                projectExtensionRelationManager.delete(projectExtensionRelation);
            }
        }

        //删除project-attach
        List<ProjectAttach> projectAttachList = projectAttachManager.getProjectAttachListByProjectId(projectId);
        if (projectAttachList != null) {
            for (ProjectAttach projectAttach : projectAttachList) {
                projectAttachManager.delete(projectAttach);
            }
        }

        entity.setIsDelete(true);
        return projectMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

    //分页查询项目信息列表
    public Pagination<ProjectDTO> list(ProjectSearchDTO projectSearchDTO) {
        Pagination<ProjectDTO> result = new Pagination<ProjectDTO>(projectSearchDTO.getCurrentPage(), projectSearchDTO.getPerPage());
        ProjectExample example = buildSearchExample(projectSearchDTO);
        int total = projectMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<ProjectDTO> data = new ArrayList<ProjectDTO>();
            List<Project> list = projectMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (Project entity : list) {
                ProjectDTO dto = ProjectDomainConvertUtils.convert(entity);
                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    /**
     * 根据查询条件提取所有记录
     *
     * @param projectSearchDTO
     * @return
     */
    public List<ProjectDTO> all(ProjectSearchDTO projectSearchDTO) {
        ProjectExample example = buildSearchExample(projectSearchDTO);

        List<ProjectDTO> data = new ArrayList<ProjectDTO>();
        List<Project> list = projectMapperExt.selectByExample(example);
        for (Project entity : list) {
            ProjectDTO dto = ProjectDomainConvertUtils.convert(entity);
            data.add(dto);
        }
        return data;
    }

    //通过项目分类编号查询项目id列表
    public List<Integer> getProjectIdsByCategoryId(Integer projectCategoryId) {
        ProjectExample example = new ProjectExample();
        ProjectExample.Criteria criteria = example.createCriteria();
        criteria.andProjectCategoryIdEqualTo(projectCategoryId);
        criteria.andIsDeleteEqualTo(false);
        List<Project> list = projectMapperExt.selectByExample(example);
        List<Integer> ids = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Project entity : list) {
                ids.add(entity.getProjectId());
            }
        }
        return ids;

    }

    //通过项目分类id列表，查询项目id列表
    public List<Integer> getProjectIdsByCategoryIds(List<Integer> projectCategoryIds, List<Integer> projectIds) {


        ProjectExample example = new ProjectExample();
        ProjectExample.Criteria criteria = example.createCriteria();
        if (projectCategoryIds != null && projectCategoryIds.size() > 0)
            criteria.andProjectCategoryIdIn(projectCategoryIds);
        criteria.andIsDeleteEqualTo(false);
        List<Project> list = projectMapperExt.selectByExample(example);
        List<Integer> ids = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Project entity : list) {
                ids.add(entity.getProjectId());
            }
        }
        if (projectIds != null && projectIds.size() > 0) {
            for (Integer id : projectIds) {
                if (!ids.contains(id)) {
                    ids.add(id);
                }
            }
        }
        return ids;
    }

    public List<ProjectDTO> listForOrg() {
        ProjectSearchDTO search = new ProjectSearchDTO();
        OrganizationDTO orgDto = organizationManager.getByOrgCode(UserUtils.getUser().getWorkOrg());
        search.setOrgCode(orgDto.getBusinessDeptCode());
        search.setAllowOrgEntry(true);
        List<Project> entityList = projectMapperExt.selectByExample(buildSearchExample(search));
        List<ProjectDTO> dtoList = new ArrayList<>();
        if (entityList != null && entityList.size() > 0) {
            for (Project entity : entityList) {
                dtoList.add(ProjectDomainConvertUtils.convert(entity));
            }
        }
        return dtoList;
    }

    //build查询Example
    private ProjectExample buildSearchExample(ProjectSearchDTO search) {
        ProjectExample example = new ProjectExample();
        ProjectExample.Criteria criteria = example.createCriteria();

        if (search.getProjectId() != null && search.getProjectId() > 0) {
            criteria.andProjectIdEqualTo(search.getProjectId());
        }
        if (search.getProjectCategoryId() != null && search.getProjectCategoryId() > 0) {
            criteria.andProjectCategoryIdEqualTo(search.getProjectCategoryId());
        }
        if (StringUtils.isNotBlank(search.getProjectCode())) {
            criteria.andProjectCodeEqualTo(search.getProjectCode());
        }
        if (StringUtils.isNotBlank(search.getProjectName())) {
            criteria.andProjectNameEqualTo(search.getProjectName());
        }
        if (StringUtils.isNotBlank(search.getOrgCode())) {
            criteria.andOrgCodeEqualTo(search.getOrgCode());
        }
        if (search.getDisabled() != null) {
            criteria.andDisabledEqualTo(search.getDisabled());
        }
        if (search.getAllowOrgEntry() != null) {
            criteria.andAllowOrgEntryEqualTo(search.getAllowOrgEntry());
        }
        criteria.andProjectCategoryIdNotEqualTo(16);
        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("project_id asc");
        }
        return example;
    }

}
